<?php
/**
 * PC版投注处理
 */
defined('IN_YuLin') || exit('NO PERMIT!');
include_once (ROOT_PATH.'module/lottery/lottery_play_conf.inc.php');
include_once (ROOT_PATH.'module/lottery/lottery_play_betting.inc.php');
UserLogin();
$bettingResInfo = array(
    'status' => 'success',
    'msg'    => '投注成功',
    'data'   => '',
);
$post = json_decode($_POST['data']);
// 查询提交投注的彩种信息
$getLottSql = 'SELECT title, ename, sname, ptid, cate_id FROM ' . Table('lottery') . ' WHERE id = ' . $post->lott_id;
$lottInfo   = $db->getrow($getLottSql);
$param      = array('uid' => $_uid, 'platform' => $post->platform, 'post' => $post->cart);
switch ($lottInfo['ptid']){
    case 'ssc':
        $param['chasePeriodData'] = $post->chasePeriodData;
        $orderData = betting_ssc($param);
        break;
}

// 检查账户余额， 是否足够一次性支付所有的投注
if ($_user['money'] < $orderData['main']['amount']){
    $bettingResInfo['status'] = 'error';
    $bettingResInfo['msg']    = '账户余额不足支付所有投注';
}else{
    do_order($db, $orderData, $bettingResInfo);
}
echo json_encode($bettingResInfo);


function do_order ($db, $data, &$res){
    if(!$data['main'] || !$data['item']) {
        $res['status'] = 'error';
        $res['msg']    = '网络繁忙,请刷新重试!';
        return;
    }
    // 记录主订单表信息
    $orderId = $db->add('lottery_order_main', $data['main']);
    if (!$orderId){
        $res['status'] = 'error';
        $res['msg']    = '网络繁忙,请刷新重试!';
        return;
    }
    foreach($data['item'] as $key => $val){
        $val['o_id']    = $orderId;
        $execSql = 'INSERT INTO ' . Table('lottery_order_item') . ' SET ' . CreateUpdateSql($val);
        $itemid = $db->exec($execSql);
        if (!$itemid){
            $res['status'] = 'error';
            $res['msg']    = '网络繁忙,请刷新重试!';
            break;
        }
    }
    $tmp = [];
    $tmp['uid']     = $data['main']['uid'];
    $tmp['tid']     = 'order_add';
    $tmp['lkey']    = $data['main']['order_no'];
    $tmp['money']   = $data['main']['amount'];
    $tmp['balance'] = -$data['main']['amount'];
    $tmp['notes']   = '下注购买彩票：' . $data['lott_title'] . '-' . $data['code'];
    MoneyLog($tmp);
    
    // 代理返点相关，这里应该在下单后操作
    fanDian($data['main'], $orderId);
    return $res;
}